import { HttpException, Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types, ClientSession } from 'mongoose';
import { Record } from 'src/schemas/record.schema';
import CreateRecordDto from './dto/create.record.dto';
import UpdateRecordDto from './dto/update.record.dto';

@Injectable()
export class RecordService {
  constructor(
    @InjectModel(Record.name) private readonly recordModel: Model<Record>,
  ) {}

  // 添加记录
  async addRecord(userId: string, record: CreateRecordDto, date: string) {
    const { motionId, ...rest } = record;
    return await this.recordModel.create({
      userId,
      date,
      motionId: new Types.ObjectId(motionId),
      ...rest,
    });
  }

  async addRecords(userId: string, records: CreateRecordDto[], date: string) {
    return await this.recordModel.insertMany(
      records.map((item) => {
        const { motionId, ...rest } = item;
        return {
          userId,
          date,
          motionId: new Types.ObjectId(item.motionId),
          ...rest,
        };
      }),
    );
  }

  async getDayData(userId: string, date: string) {
    const data = await this.recordModel
      .find({
        userId,
        date,
      })
      .select('-date -userId')
      .populate({
        path: 'motionId',
        select: 'name group category tool img',
      })
      .lean();

    return data.map((motion) => {
      const motionData: any = { ...motion };
      motionData.name = motionData.motionId.name;
      motionData.group = motionData.motionId.group;
      motionData.category = motionData.motionId.category;
      motionData.tool = motionData.motionId.tool;
      motionData.img = motionData.motionId.img;
      motionData.motionId = motionData.motionId._id;
      return motionData;
    });
  }

  async getRecordById(recordId: string) {
    const data = await this.recordModel
      .findById(recordId)
      .select('-userId -createdAt -updatedAt')
      .populate({
        path: 'motionId',
        select: 'name',
      })
      .lean();

    const motionData: any = { ...data };
    motionData.name = motionData.motionId.name;
    motionData.motionId = motionData.motionId._id;

    return motionData;
  }

  async deleteRecord(recordId: string) {
    return await this.recordModel.deleteOne({
      _id: recordId,
    });
  }

  async deleteRecordsByMotion(
    userId: string,
    motionId: string,
    session?: ClientSession,
  ) {
    return await this.recordModel.deleteMany(
      { userId, motionId: new Types.ObjectId(motionId) },
      { session },
    );
  }

  async updateRecord(record: UpdateRecordDto) {
    return await this.recordModel.updateOne({ _id: record._id }, record);
  }

  async existsByMotionId(motionId: string): Promise<boolean> {
    const count = await this.recordModel
      .countDocuments({ motionId: new Types.ObjectId(motionId) })
      .limit(1);
    return count > 0;
  }

  async getMonthStats(userId: string, month: string) {
    // 验证月份格式并创建日期对象
    const date = new Date(`${month}-01`);

    // 计算下个月的第一天
    const nextMonth = new Date(date);
    nextMonth.setMonth(date.getMonth() + 1);

    // 格式化为YYYY-MM-DD格式的字符串
    const startDate = date.toISOString().split('T')[0];
    const endDate = nextMonth.toISOString().split('T')[0];

    // 使用日期范围查询替代正则匹配
    const records = await this.recordModel
      .find({
        userId,
        date: {
          $gte: startDate,
          $lt: endDate,
        },
      })
      .lean();

    const stats = {};

    records.forEach((record) => {
      if (!stats[record.date]) {
        stats[record.date] = 1;
      } else {
        stats[record.date] += 1;
      }
    });

    return stats;
  }
}
